package com.sw.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sw.model.User;
import com.sw.service.UserService;
import com.sw.util.CreateNumberUtil;
import com.sw.util.SendSMSUtil;

import net.sf.json.JSONObject;

@Controller
@RequestMapping(value="/user")
public class UserController {

	@Autowired
	private UserService userService;
	/**
	 * 注册
	 * @param user
	 * @return
	 */
	@RequestMapping(value="/register",method=RequestMethod.POST)
	public @ResponseBody String register(User user){
		System.out.println(user.getPhone());
		boolean result = userService.register(user); 
		JSONObject jsonObject = new JSONObject();  
		if(result){
		    jsonObject.put("msg", "success");  
		}else{
			jsonObject.put("msg", "手机号已经被注册！");  
		}
		 
	     return jsonObject.toString();
	}
	
	/**
	 * 登录
	 * @param user
	 * @return
	 */
	@RequestMapping(value="/login",method=RequestMethod.POST)
	public @ResponseBody String login(User user){
		boolean result = userService.login(user);
		JSONObject jsonObject = new JSONObject();  
		if(result){
		    jsonObject.put("msg", "success");  
		}else{
			jsonObject.put("msg", "用户名或密码错误！");  
		}
		 
	     return jsonObject.toString();
	}
	
	/**
	 * 修改密码
	 * @param user
	 * @return
	 */
	@RequestMapping(value="/changePassword",method=RequestMethod.POST)
	public @ResponseBody String changePassword(User user){
		boolean result = userService.changePassword(user);
		JSONObject jsonObject = new JSONObject();  
		if(result){
		    jsonObject.put("msg", "success");  
		}else{
			jsonObject.put("msg", "修改密码失败！");  
		}
		 
	     return jsonObject.toString();
	}
	
	/**
	 * 发送短信（注册）
	 * @param phone
	 * @return
	 */
	@RequestMapping(value="/sendMSM/{phone}")
	public @ResponseBody String sendMessage(@PathVariable("phone") String phone){
		int mobile_code = CreateNumberUtil.getRandomNumber();
		boolean result = SendSMSUtil.sendSMSValidataCode(phone, "402852845507f30f0155235a358a0035", mobile_code);
		JSONObject jsonObject = new JSONObject();  
		if(result){
		    jsonObject.put("msg", mobile_code);  
		}else{
			jsonObject.put("msg", "error");  
		}
	     return jsonObject.toString();
	} 
}
